package com.zhongyu.config;

import com.zhongyu.pojo.User;
import com.zhongyu.service.PermissionService;
import com.zhongyu.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import java.util.List;


public class SmbmsRealm extends AuthorizingRealm {

 private  UserService userService;

    public void setUserService(UserService userService){

        this.userService=userService;
    }
    private   PermissionService permissionService;

    public  void   setPermissionService(PermissionService permissionService){
        this.permissionService=permissionService;
    }

    /**
     * 提供授权判定
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    User user= (User) principalCollection.getPrimaryPrincipal();
List<String> permCodes= permissionService.searchPermCodes(user.getUserRole());
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
info.addStringPermissions(permCodes);
        return info;
    }

    /**
     * 提供认证信息
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userCode= (String) authenticationToken.getPrincipal();
        User user=userService.searchByUserCode(userCode);
        if (user==null){
            return  null;
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),super.getName());
        return info;
    }
}
